package com.gitee.ricesugar.mall.servlets;

import com.gitee.ricesugar.mall.model.POJO.DTO.LoginDTO;
import com.gitee.ricesugar.mall.model.Service.AccountService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet(name = "LoginServlet", value = "/login")
public class LoginServlet extends HttpServlet {

    private AccountService accountService;

    @Override
    public void init() throws ServletException {
        super.init();
        try {
            accountService = new AccountService();
        } catch (SQLException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String checkCode = request.getParameter("capture");

        HttpSession session = request.getSession();
        if(!checkCode.equals(session.getAttribute("checkCode"))){
            response.sendRedirect("/login.jsp?error=2");
            return;
        }

        LoginDTO loginDTO = null;
        try {
            loginDTO = accountService.login(username,password);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        if(loginDTO != null){
            Cookie cookie = new Cookie("login","username=" + username + "password=" + password);
            cookie.setMaxAge(60*60*24);
            response.addCookie(cookie);
            try {
                response.sendRedirect("/");
            }catch (Exception e){
                e.printStackTrace();
            }
        }else{
            response.sendRedirect("/login.jsp?error=1");
        }
    }
}
